/*
 * Dispatcher.c
 *
 *  Created on: May 27, 2013
 *      Author: dianagorun
 */
#include <stdio.h>
#include <stdlib.h>
#include "CPU.h"
#include "Queue.h"
#include "Dispatcher.h"
#include "Process.h"

ProcessPtr idle;

int load_next_process(){
		if(queue_isEmpty(ready_queue) !=TRUE){
		currentProcess->next_step = pcbTable[ready_queue->head->PID].next_step;
		currentProcess->process = pcbTable[ready_queue->head->PID].process;
		currentProcess->queue = pcbTable[ready_queue->head->PID].queue;
		currentProcess->state = pcbTable[ready_queue->head->PID].state;
		return 1;
		}else{
			idle = process_init(2,0, NULL,IDLE_PROCESS,"IDLE", -1, 0, 0,0);
			currentProcess->next_step = 0;
			currentProcess->process = idle;
			currentProcess->queue = NULL;
			currentProcess->state = RUNNABLE;
			return 0;
		}

	}

void new_dispatch(){
	if(currentProcess->process!=NULL && currentProcess->process->id != -1){
		printf("P%i is Done!\n\n",currentProcess->process->id);
	}
	int q = load_next_process();
	if(q == 1 && currentProcess->process->id > -1){
		remove_queue(ready_queue);
		printf("P%i -running\nready_queue ", currentProcess->process->id);
		print_queue(ready_queue);
	}

}
void dispatch(INTERUPT_TYPE it){
	if(it == TIMER_INTERUPT ){
		PCB_init(currentProcess->process,currentProcess->next_step);
		int q = load_next_process();
		if(q == 1 && currentProcess->process->id > -1){
			remove_queue(ready_queue);
			printf("Timer Interrupt\n\n");
			printf("P%i -running\nready_queue ", currentProcess->process->id);
			print_queue(ready_queue);
		}
		//printf("\n");
	}
}
